package or;

import org.junit.jupiter.api.Test;

import java.util.*;

public class T1361 {

    int cnt=0;
    public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < n; i++) {
            if (leftChild[i] != -1 && !set.add(leftChild[i])) {
                return false;
            }
            if (rightChild[i] != -1 && !set.add(rightChild[i])) {
                return false;
            }
        }
        int root=-1;
        for (int i = 0; i < n; i++) {
            if (!set.contains(i)){
                root=i;
                break;
            }
        }
        aVoid(n,root,leftChild,rightChild);
        return cnt==n;

    }

    public void aVoid(int n,int root, int[] leftChild, int[] rightChild){
        if (root==-1){
            return;
        }
        cnt++;
        aVoid(n,leftChild[root],leftChild,rightChild);
        aVoid(n,rightChild[root],leftChild,rightChild);
        return;
    }


    @Test
    public void test() {
        int[] leftChild = {1, -1, 3, -1};
        int[] rightChild = {2, 3, -1, -1};
        System.out.println(validateBinaryTreeNodes(4, leftChild, rightChild));

    }
}
